package com.baymax.test.scene.replace

import android.util.Log
import com.baymax.lib.replace.ReplacerFunction


/**
 * 对字符串做分段处理
 * 先对[itemSplitChar] 分段，后对[contentSplitChar]分段
 * 之后对[contentSplitChar]分段出来的内容做替换
 * ex:      aaaaa,bbbb|cccc,ddddd
 * result : aaaa 替换为 bbbb ，cccc ->替换为 dddd
 */
class SimpleReplacer(
    rules: String,
    private val itemSplitChar: Char,
    private val contentSplitChar: Char
) : ReplacerFunction<String, String>() {

    class ReplaceRule(val origin: String, spiltChar: Char) : (String) -> String {
        val split = origin.split(spiltChar)
        val valid = split.size == 2
        val key = split.firstOrNull().orEmpty()
        val value = split.getOrNull(1).orEmpty()
        override fun invoke(p1: String): String {
            return p1.replace(key, value)
        }

        override fun toString(): String {
            return "ReplaceRule(origin='$origin', valid=$valid)"
        }
    }

    private val replaceRules: List<ReplaceRule> by lazy {
        rules.split(itemSplitChar)
            .mapNotNull { r -> ReplaceRule(r, contentSplitChar).takeIf { it.valid } }
    }

    init {
        replaceRules.forEach {
            add(it.key, it)
        }
    }

    override fun finder(t: String): List<String> {
        return replaceRules.mapNotNull { if (t.contains(it.key)) it.key else null }
    }

}